const http = require('http');
const fs = require('fs');
const path = require('path');

var arr = process.argv;

http.createServer((req, res) => {

    res.writeHead(200, {
        "Content-Type": "text/html;charest=utf-8"
    })

    var filePath = path.join(__dirname, './fileReader2.js');
    if (arr[2]) {
        var filePath1 = path.join(__dirname, arr[2]);
        if (fs.existsSync(filePath1)) {
            fs.open(filePath1, (err, fd) => {
                if (err) {
                    console.log(err);
                } else {
                    fs.read(fd, (err, bytesRead, buffer) => {
                        if (err) {
                            console.log(err);
                        } else {
                            res.end(buffer.toString('utf-8'));
                        }
                    })
                }
            })
        }

    } else {
        fs.open(filePath, (err, fd) => {
            if (err) {
                console.log(err);
            } else {
                fs.read(fd, (err, bytesRead, buffer) => {
                    if (err) {
                        console.log(err);
                    } else {
                        res.end(buffer.toString('utf-8'));
                    }
                })
            }
        })
    }

}).listen(8081);
console.log('server listening on port');